package com.example.jack.community.view.me.personinfo;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Vibrator;
import android.provider.MediaStore;
import android.support.annotation.NonNull;
import android.support.design.widget.BottomSheetBehavior;
import android.support.percent.PercentRelativeLayout;
import android.support.v4.widget.NestedScrollView;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.example.jack.community.R;
import com.example.jack.community.view.me.BlackStatusActivity;
import com.lzy.imagepicker.ImagePicker;
import com.lzy.imagepicker.bean.ImageItem;
import com.lzy.imagepicker.ui.ImageGridActivity;
import com.lzy.imagepicker.view.CropImageView;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import cn.pedant.SweetAlert.SweetAlertDialog;
import uk.co.senab.photoview.PhotoView;

import static android.R.attr.path;
import static com.example.jack.community.R.id.img_menu;
import static com.example.jack.community.R.id.pho_user_logo;

/**
 * 用户头像
 */
public class My_LogoActivity extends BlackStatusActivity {

    private static final int REQUEST_CODE_SELECT = 1;
    private static final int IMAGE_PICKER = 2;
    @BindView(R.id.img_back)
    ImageView imgBack;
    @BindView(R.id.txt_back)
    TextView txtBack;
    @BindView(img_menu)
    ImageView imgMenu;
    @BindView(pho_user_logo)
    PhotoView phoUserLogo;
    @BindView(R.id.bottomsheet)
    NestedScrollView bottomsheet;
    @BindView(R.id.activity_res_pass)
    PercentRelativeLayout activityResPass;
    @BindView(R.id.txt_cam)
    TextView txtCam;
    @BindView(R.id.txt_pho)
    TextView txtPho;
    @BindView(R.id.txt_save)
    TextView txtSave;
    private BottomSheetBehavior mBottomSheetBehavior;
    private ArrayList<ImageItem> selImageList; //当前选择的所有图片
    private int maxImgCount = 8;               //允许选择图片最大数
    private static final String TAG = "TonJie";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.my_my__logo);
        ButterKnife.bind(this);
        mBottomSheetBehavior = BottomSheetBehavior.from(bottomsheet);
        //当底部菜单弹出时,点击外部区域，菜单关闭
        Bottom();
        imageprice();
        pho();
        SharedPreferences sharedPreferences = getSharedPreferences("data", MODE_PRIVATE);
        String user_logo = sharedPreferences.getString("user_logo", "0");
        Log.d(TAG, "onCreate: " + user_logo);

        if (user_logo.equals("0")) {
            Glide.with(this).load(R.drawable.login_users).
                    into(phoUserLogo);
            Log.d(TAG, "onCreateView: 等于0");
        }else{
            Glide.with(this).load(user_logo).
                    into(phoUserLogo);
            Log.d(TAG, "onCreateView: 不等于0");
        }
    }

    private void pho() {
        phoUserLogo.setOnLongClickListener(new View.OnLongClickListener() {
            @Override
            public boolean onLongClick(View view) {
                Vibrator vibrator = (Vibrator) getApplication().getSystemService(getApplication().VIBRATOR_SERVICE);
                vibrator.vibrate(400);
                final SweetAlertDialog dialog = new SweetAlertDialog(My_LogoActivity.this, SweetAlertDialog.NORMAL_TYPE);
                dialog.getProgressHelper().setBarColor(R.color.colorPrimary);
                dialog.setTitleText("保存图片")
                        .setConfirmText("确定")
                        .setConfirmClickListener(new SweetAlertDialog.OnSweetClickListener() {
                            @Override
                            public void onClick(SweetAlertDialog sweetAlertDialog) {
                                Bitmap image = ((BitmapDrawable) phoUserLogo.getDrawable()).getBitmap();
                                saveImageToGallery(My_LogoActivity.this, image);
                                dialog.cancel();
                            }
                        })
                        .showCancelButton(true)
                        .setCancelText("取消")
                        .setCancelClickListener(new SweetAlertDialog.OnSweetClickListener() {
                            @Override
                            public void onClick(SweetAlertDialog sweetAlertDialog) {
                                dialog.cancel();
                            }
                        });
                dialog.show();
                return true;
            }
        });
    }

    /**
     * 设置图片选择库
     */
    private void imageprice() {
        ImagePicker imagePicker = ImagePicker.getInstance();
        imagePicker.setImageLoader(new PicassoImageLoader());   //设置图片加载器
        imagePicker.setShowCamera(true);  //显示拍照按钮
        imagePicker.setCrop(true);        //允许裁剪（单选才有效）
        imagePicker.setSaveRectangle(false); //是否按矩形区域保存
        imagePicker.setSelectLimit(1);    //选中数量限制
        imagePicker.setStyle(CropImageView.Style.CIRCLE);  //裁剪框的形状
        imagePicker.setFocusWidth(800);   //裁剪框的宽度。单位像素（圆形自动取宽高最小值）
        imagePicker.setFocusHeight(800);  //裁剪框的高度。单位像素（圆形自动取宽高最小值）
        imagePicker.setOutPutX(1000);//保存文件的宽度。单位像素
        imagePicker.setOutPutY(1000);//保存文件的高度。单位像素
        imagePicker.setMultiMode(false);
    }

    /**
     * 当底部菜单弹出时,点击外部区域，菜单关闭
     */
    private void Bottom() {
        /**
         * 设置回调
         */
        mBottomSheetBehavior.setBottomSheetCallback(new BottomSheetBehavior.BottomSheetCallback() {
            @Override
            public void onStateChanged(@NonNull View bottomSheet, int newState) {
                switch (newState) {
                    case BottomSheetBehavior.STATE_EXPANDED:
                        activityResPass.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View view) {
                                mBottomSheetBehavior.setState(BottomSheetBehavior.STATE_COLLAPSED);
                            }
                        });
                }
            }

            @Override
            public void onSlide(@NonNull View bottomSheet, float slideOffset) {

            }
        });
    }

    @OnClick({R.id.txt_cam, R.id.txt_save, R.id.txt_pho, R.id.txt_back, img_menu})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.txt_cam:
                Intent intent = new Intent(this, ImageGridActivity.class);
                intent.putExtra(ImageGridActivity.EXTRAS_TAKE_PICKERS, true); // 是否是直接打开相机
                startActivityForResult(intent, REQUEST_CODE_SELECT);
                break;
            case R.id.txt_save:
                Bitmap image = ((BitmapDrawable) phoUserLogo.getDrawable()).getBitmap();
                saveImageToGallery(My_LogoActivity.this, image);
                break;
            case R.id.txt_pho:
                Intent intents = new Intent(this, ImageGridActivity.class);
                startActivityForResult(intents, IMAGE_PICKER);
                break;
            case R.id.img_back://返回
                startActivity(new Intent(My_LogoActivity.this, Per_infoActivity.class));
                finish();
                break;
            case R.id.txt_back://返回
                startActivity(new Intent(My_LogoActivity.this, Per_infoActivity.class));
                finish();
                break;
            case img_menu://底部菜单
                if (mBottomSheetBehavior.getState() == BottomSheetBehavior.STATE_EXPANDED) {
                    mBottomSheetBehavior.setState(BottomSheetBehavior.STATE_COLLAPSED);
                } else if (mBottomSheetBehavior.getState() == BottomSheetBehavior.STATE_COLLAPSED) {
                    mBottomSheetBehavior.setState(BottomSheetBehavior.STATE_EXPANDED);
                }

                break;
        }
    }

    /**
     * @param requestCode
     * @param resultCode
     * @param data
     */
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == ImagePicker.RESULT_CODE_ITEMS) {
            mBottomSheetBehavior.setState(BottomSheetBehavior.STATE_COLLAPSED);
            if (data != null && requestCode == REQUEST_CODE_SELECT) {
                selImageList = (ArrayList<ImageItem>) data.getSerializableExtra(ImagePicker.EXTRA_RESULT_ITEMS);
                Log.d(TAG, "onActivityResult: " + selImageList.get(0).path);
                Glide.with(this).load(selImageList.get(0).path).into(phoUserLogo);
                SharedPreferences.Editor editor = getSharedPreferences("data", MODE_PRIVATE).edit();
                editor.putString("user_logo", selImageList.get(0).path);
                editor.apply();
            } else {

            }
            if (data != null && requestCode == IMAGE_PICKER) {
                ArrayList<ImageItem> images = (ArrayList<ImageItem>) data.getSerializableExtra(ImagePicker.EXTRA_RESULT_ITEMS);
                Glide.with(this).load(images.get(0).path).into(phoUserLogo);
                Log.d(TAG, "onActivityResult: " + images.get(0).path);
                SharedPreferences.Editor editor = getSharedPreferences("data", MODE_PRIVATE).edit();
                editor.putString("user_logo", images.get(0).path);
                editor.apply();
            } else {

            }
        }
    }

    /**
     * 保存图片到系统相册
     */
    public void saveImageToGallery(Context context, Bitmap bmp) {
        // 首先保存图片
        File appDir = new File(Environment.getExternalStorageDirectory(), "Boohee");
        if (!appDir.exists()) {
            appDir.mkdir();
        }
        String fileName = System.currentTimeMillis() + ".jpg";
        File file = new File(appDir, fileName);
        try {
            FileOutputStream fos = new FileOutputStream(file);
            bmp.compress(Bitmap.CompressFormat.JPEG, 100, fos);
            fos.flush();
            fos.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

        // 其次把文件插入到系统图库
        try {
            MediaStore.Images.Media.insertImage(context.getContentResolver(),
                    file.getAbsolutePath(), fileName, null);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        // 最后通知图库更新
        context.sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.parse("file://" + path)));

        My_LogoActivity.this.runOnUiThread(new Runnable() {
            @Override
            public void run() {
                Toast.makeText(My_LogoActivity.this, "保存图片成功", Toast.LENGTH_SHORT).show();
                mBottomSheetBehavior.setState(BottomSheetBehavior.STATE_COLLAPSED);
            }
        });
    }
}